<?php

namespace App\Jobs;

use Illuminate\Bus\Queueable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Asymptix\HtmlDomParser\HtmlDomParser;
use Illuminate\Support\Facades\Log;
use App\Jobs\updateSectionsByUrlFromQuanShuWu;
use App\Models\Book;
use App\Models\Operation;
use GuzzleHttp\Client;
use App\Models\Category;

class getBookSectionsFromQuanShuWu implements ShouldQueue {
	use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
	
	private $url;
	
	/**
	 * Create a new job instance.
	 *
	 * @return void
	 */
	public function __construct($url) {
		$this->url = $url;
	}
	
	/**
	 * Execute the job.
	 *
	 * @return void
	 */
	public function handle() {
		$html = new HtmlDomParser();
		$html->loadUrl($this->url);
		$bookName = $html->find('h1', 0)->plaintext;
		$bookAuthor = substr($html->find('#bookinfo .ti p', 0)->plaintext, 9);
		$book = Book::where('name', $bookName)->where('author', $bookAuthor)->first();
		if(is_null($book)) {
			$bookCategory = substr($html->find('#bookinfo .ti ul li', 0)->find('a', 0)->plaintext, 0, 6);
			$category = Category::where('name', 'like', '%'.$bookCategory.'%')->first();
			$bookFontNum = $html->find('#bookinfo .ti ul li', 2)->find('label', 0)->plaintext;
			$bookAbstract = $html->find('#bookintro', 0)->find('#bookintroinner', 0)->plaintext;
			$book = Book::create([
				'name' => $bookName,
				'author' => $bookAuthor,
				'font_num' => $bookFontNum,
				'abstract' => $bookAbstract,
				'source' => Book::SHUQIBA,
				'href' => $this->url,
			]);
			if(!is_null($category)) {
				$book->category_id = $category->id;
				$book->save();
			}
			$img = $html->find('#bookinfo .fm img', 0)->src;
			if(!strpos($img, 'nocover')) {
				$client = new Client();
				$nName = public_path('uploads/covers/'.$book->id.'-cover.jpg');
				$client->get($img, ['save_to' => $nName]);
				$book->thumbnail = $book->id . '-cover.jpg';
				$book->save();
			}else {
				$book->thumbnail = 'nocover.jpg';
				$book->save();
			}
			unset($bookAuthor);
			unset($bookCategory);
			unset($bookFontNum);
			unset($bookAbstract);
			unset($category);
		}
		$i=0;
		$num = $book->completed ? $book->sections->count() : 0;
		$sections = $html->find('#readlist ul', 0)->find('li');
		foreach ($sections as $section) {
			$i++;
			if($i <= $num) continue;
			dispatch(new updateSectionsByUrlFromQuanShuWu('http://www.quanshuwu.com'.$section->find('a', 0)->href, $i, count($sections), $book));
		}
		$book->completed = true;
		$book->save();
		Operation::create([
			'action' => '小说采集-队列',
			'content' => $book->name.' => 加入队列完成，需采集： '.($i-$num).' 章',
		]);
		return 1;
	}
}
